package com.kk.blog.service;

//标签

import com.kk.blog.dao.TagRepository;
import com.kk.blog.pojo.Tag;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagRepository tagRepository;

    @Transactional
    @Override
    public Tag saveTag(Tag tag) {
        return tagRepository.save(tag);
    }

    @Transactional
    @Override
    public Tag getTag(Long id) { //单个标签的查询方法,通过id
        return tagRepository.getById(id);
    }

    @Transactional
    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagRepository.findAll(pageable);
    }

    @Override
    public List<Tag> listTag() {
        return tagRepository.findAll();
    }

    @Override
    public List<Tag> listTag(String ids) { //1,2,3
        return tagRepository.findAllById(convertToList(ids));
    }
    private List<Long> convertToList(String ids){
        List<Long> list = new ArrayList <>();
        if(!"".equals(ids)&& ids != null) {
            String[] idarray = ids.split( ",");
            for (int i=0; i < idarray.length; i++) {
                list.add(new Long(idarray[i]));
                }
            }
            return list;
        }


    @Override
    public List<Tag> listTagTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = PageRequest.of(0,size,sort);

        return tagRepository.findTop(pageable);

    }

    @Transactional
    @Override
    public Tag updateTag(Long id, Tag tag) throws NotFoundException { //更新方法要回显信息

        Tag t = tagRepository.getById(id);
        if (t == null){
            throw new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(tag,t); //把 type对象 拷贝到 t对象

        return tagRepository.save(t);
    }

    @Override
    public Tag getTagByName(String name) {
        return tagRepository.findByName(name);
    }

    @Transactional
    @Override
    public void deleteTag(Long id) {
        tagRepository.deleteById(id);
    }

}
